// modules/settingModule/pages/address/list/index.js
import { reqAddressList,reqDelAddress} from "../../../apis/address"
import {swipeCellBehavior} from "../../../../../behaviors/swipeCell"
 // 获取全局的应用实例
 const app = getApp()
Page({
  behaviors:[swipeCellBehavior],
  // 页面的初始数据
  data: {
    addressList: []
  },
// 切换收货地址
  changeAddress(event) {
    // 判断是否是从订单结算页面进入
    if(this.flag !=='1')return
    // // 获取到点击的收货地址 id
   const addressId = event.currentTarget.dataset.id
    // 从收货地址列表中获取到获取到点击的收货地址详细信息
  const address=this.data.addressList.find(item =>item.id ===addressId)
   // 如果获取成功，将数据存储到 全局对象globalData 中
   if(address){
     app.globalData.address=address
     wx.navigateBack()
   }

  },
  // 获取收货地址
  async getAddressList() {
    // 调用 API，获取收货地址
    const { data: addressList } = await reqAddressList()
    this.setData({
      addressList
    })
    // console.log(addressList);
  },
  // 去编辑页面
  toEdit(event) {
    // console.log(event.currentTarget.dataset.id);
    const {id}=event.currentTarget.dataset

    wx.navigateTo({
      url: `/modules/settingModule/pages/address/add/index?id=${id}`
    })
  },
  //删除收获地址
async deleteAddress(e){
    const {id}=e.currentTarget.dataset
    await reqDelAddress(id)
    wx.toast({title:'删除收获地址成功'})
    this.getAddressList()

  },
  onLoad(options){
    this.getAddressList()
    //区分是否从结算页面到地址列表的关键字
    this.flag=options.flag
  }
})
